<template>
    <view style="padding: 15px;">
        <u-form ref="validateFormRef" :model="validateForm.value" :label-width="150">
            <u-form-item label="广告图片" prop="sysFileId" required>
                <u-upload ref="uUpload" :multiple="false" :auto-upload="false" :max-count="1" :show-progress="false"
                          @on-remove="onRemove($event)" @on-choose-complete="onChooseComplete($event)"></u-upload>
            </u-form-item>
            <u-form-item label="类型" prop="type" required>
                <u-input type="select" :select-open="validateForm.controls.type.isShow" v-model="validateForm.controls.type.textDesc"
                         placeholder="请选择类型" @click="validateForm.controls.type.isShow = true; $forceUpdate();"></u-input>
            </u-form-item>
            <u-form-item label="跳转到url" prop="navUrl">
                <u-input v-model="validateForm.value.navUrl" placeholder="请输入跳转到url"/>
            </u-form-item>
            <u-form-item label="跳转到商品" prop="navGoodsId" right-icon="arrow-right">
                <u-input v-model="validateForm.value.navGoodsTitle" type="textarea" height="40" :clearable="false" placeholder="请选择跳转的商品"
                         @click="navigateTo(`/pages/common/ad/ad-nav-goods-select/index`, null, validateForm.value)"/>
            </u-form-item>
            <u-form-item label="跳转到店铺" prop="navStoreId">
                <u-input v-model="validateForm.value.navStoreName" type="select" placeholder="请选择跳转的店铺" right-icon="arrow-right"
                         @click="navigateTo(`/pages/common/ad/ad-nav-store-select/index`, null, validateForm.value)"/>
            </u-form-item>
            <u-form-item label="跳转到二级系统分类" prop="navSystemClassGrade2Id">
                <u-input v-model="validateForm.value.navSystemClassGrade2Name" type="select" placeholder="请选择跳转的二级系统分类" right-icon="arrow-right"
                         @click="navigateTo(`/pages/common/ad/ad-nav-store-class-grade2-select/index`, null, validateForm.value)"/>
            </u-form-item>
            <u-form-item label="跳转到商城动态分类" prop="navCommunityDynamicTypeId">
                <u-input v-model="validateForm.value.navCommunityDynamicTypeName" type="select" placeholder="请选择跳转的商城动态分类" right-icon="arrow-right"
                         @click="navigateTo(`/pages/common/ad/ad-nav-community-dynamic-type-select/index`, null, validateForm.value)"/>
            </u-form-item>
            <u-form-item label="跳转到商城动态" prop="navCommunityDynamicId" right-icon="arrow-right">
                <u-input v-model="validateForm.value.navCommunityDynamicTitle" type="textarea" height="40" :clearable="false" placeholder="请选择跳转的商城动态"
                         @click="navigateTo(`/pages/common/ad/ad-nav-community-dynamic-select/index`, null, validateForm.value)"/>
            </u-form-item>
            <u-form-item label="开始时间" prop="startTime" required>
                <u-input type="select" :select-open="validateForm.controls.startTime.isShow"
                         v-model="validateForm.value.startTime" placeholder="请选择开始时间"
                         @click="validateForm.controls.startTime.isShow = true; $forceUpdate();"/>
            </u-form-item>
            <u-form-item label="结束时间" prop="endTime" required>
                <u-input type="select" :select-open="validateForm.controls.endTime.isShow"
                         v-model="validateForm.value.endTime" placeholder="请选择结束时间"
                         @click="validateForm.controls.endTime.isShow = true; $forceUpdate();"/>
            </u-form-item>
            <u-form-item label="状态" prop="status" required>
                <u-input type="select" :select-open="validateForm.controls.status.isShow" v-model="validateForm.controls.status.textDesc"
                         placeholder="请选择状态" @click="validateForm.controls.status.isShow = true; $forceUpdate();"></u-input>
            </u-form-item>
            <u-form-item label="显示顺序" prop="displayOrder">
                <u-input v-model="validateForm.value.displayOrder" placeholder="请输入显示顺序（可选）"/>
            </u-form-item>
        </u-form>

        <u-button type="error" @click="submit">提交</u-button>

        <u-select mode="single-column" label-name="name" value-name="code" :mask-close-able="false"
                  v-model="validateForm.controls.type.isShow" :list="validateForm.controls.type.options"
                  :default-value="validateForm.controls.type.defaultValue"
                  @cancel="validateForm.controls.type.isShow = false; $forceUpdate();"
                  @confirm="UFormUtil.selectSingleColumnConfirm($event, validateForm.controls.type)"></u-select>

        <u-picker mode="time" :mask-close-able="false" v-model="validateForm.controls.startTime.isShow"
                  :default-time="validateForm.value.startTime" :params="pickerFormatDatetime"
                  @cancel="validateForm.controls.startTime.isShow = false; $forceUpdate();"
                  @confirm="UFormUtil.timeConfirm($event, validateForm.controls.startTime)"></u-picker>

        <u-picker mode="time" :mask-close-able="false" v-model="validateForm.controls.endTime.isShow"
                  :default-time="validateForm.value.endTime" :params="pickerFormatDatetime"
                  @cancel="validateForm.controls.endTime.isShow = false; $forceUpdate();"
                  @confirm="UFormUtil.timeConfirm($event, validateForm.controls.endTime)"></u-picker>

        <u-select mode="single-column" label-name="name" value-name="code" :mask-close-able="false"
                  v-model="validateForm.controls.status.isShow" :list="validateForm.controls.status.options"
                  :default-value="validateForm.controls.status.defaultValue"
                  @cancel="validateForm.controls.status.isShow = false; $forceUpdate();"
                  @confirm="UFormUtil.selectSingleColumnConfirm($event, validateForm.controls.status)"></u-select>
    </view>
</template>

<script>
    import {TbAdService} from "../../../../dev/services/tb-ad.service";
    import {CommonUtil} from "../../../../dev/core/utils/common.util";
    import {UFormUtil} from "../../../../dev/core/utils/u-form.util";
    import {QiniuCloudUtil} from "../../../../dev/core/utils/qiniu-cloud.util";
    import {SysFileService} from "../../../../dev/services/sys-file.service";
    import {SysDictionaryService} from "../../../../dev/services/sys-dictionary.service";

    export default {
        data() {
            return {
                validateForm: {
                    value: {
                        id: CommonUtil.randomUUID(),
                        fkId: '',
                        sysFileId: '',  // 图片sysFile.id
                        type: '',
                        navUrl: '',
                        navGoodsId: '',
                        navGoodsTitle: '',
                        navStoreId: '',
                        navStoreName: '',
                        navSystemClassGrade2Id: '',
                        navSystemClassGrade2Name: '',
                        navCommunityDynamicTypeId: '',
                        navCommunityDynamicTypeName: '',
                        navCommunityDynamicId: '',
                        navCommunityDynamicTitle: '',
                        startTime: '',
                        endTime: '',
                        status: '1',
                        displayOrder: '',
                    },
                    rules: {
                        sysFileId: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^(?=.*\S).+$/, message: '必填项!', trigger: ['change', 'blur']}
                        ],
                        type: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^(?=.*\S).+$/, message: '必填项!', trigger: ['change', 'blur']}
                        ],
                        startTime: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {
                                trigger: ['blur'],
                                asyncValidator: (rule, value, callback) => {
                                    if (this.validateForm.value.startTime && this.validateForm.value.endTime) {
                                        let startTime = new Date(this.validateForm.value.startTime).getTime();
                                        let endTime = new Date(this.validateForm.value.endTime).getTime();
                                        if (startTime > endTime) {
                                            callback(new Error('开始时间不能大于结束时间！'));
                                        } else {
                                            callback()
                                        }
                                    } else {
                                        callback()
                                    }
                                }
                            }
                        ],
                        endTime: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {
                                trigger: ['blur'],
                                asyncValidator: (rule, value, callback) => {
                                    if (this.validateForm.value.startTime && this.validateForm.value.endTime) {
                                        let startTime = new Date(this.validateForm.value.startTime).getTime();
                                        let endTime = new Date(this.validateForm.value.endTime).getTime();
                                        if (startTime > endTime) {
                                            callback(new Error('开始时间不能大于结束时间！'));
                                        } else {
                                            callback()
                                        }
                                    } else {
                                        callback()
                                    }
                                }
                            }
                        ],
                        status: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^(?=.*\S).+$/, message: '必填项!', trigger: ['change', 'blur']}
                        ],
                        displayOrder: [
                            {
                                pattern: /^(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]*))$/,
                                message: '请输入大于0的正数!',
                                trigger: ['change', 'blur']
                            }
                        ],
                    }
                },
            }
        },
        onReady() {
            const _self = this;
            this.validateForm.value.fkId = this.urlParams.fkId;
            new SysDictionaryService().optionList('tb_ad@type', null).then(result => {
                UFormUtil.setOptions(_self.validateForm.controls.type, result);
                _self.$forceUpdate();
            });
            new SysDictionaryService().optionList('status', null).then(result => {
                UFormUtil.setOptions(_self.validateForm.controls.status, result);
                _self.$forceUpdate();
            });
        },
        methods: {
            onRemove($event) {
                console.log($event);
                const _self = this;
                new SysFileService().deleteSysFile({
                    id: _self.validateForm.value.sysFileId
                }).then(result => {
                    _self.validateForm.value.sysFileId = '';
                    CommonUtil.toast("图片删除成功");
                    UFormUtil.validation(_self.$refs.validateFormRef, 'sysFileId');
                    _self.$forceUpdate()
                });
            },
            onChooseComplete($event) {
                console.log($event);
                const _self = this;
                QiniuCloudUtil.uploadToCloud(_self.validateForm.value.id, $event[$event.length - 1].file.path).then(result => {
                    if (result.status === "success") {
                        _self.validateForm.value.sysFileId = result.id;
                        CommonUtil.toast(result.message);
                    } else {
                        CommonUtil.alert(result.message);
                    }
                    UFormUtil.validation(_self.$refs.validateFormRef, 'sysFileId');
                });
            },
            submit() {
                const _self = this;
                this.$refs.validateFormRef.validate(valid => {
                    if (valid) {
                        console.log('验证通过', _self.validateForm.value);
                        CommonUtil.alert({
                            title: '提示！',
                            content: '确认提交吗？',
                            showCancel: true, // 是否显示取消按钮
                            success: function (res) {
                                if (res.cancel) { // 点击取消,默认隐藏弹框
                                } else { // 点击确定
                                    new TbAdService().saveTbAd(_self.validateForm.value).then(result => {
                                        CommonUtil.toastNavigateBack('保存成功');
                                        _self.objParams();
                                    });
                                }
                            }
                        });
                    } else {
                        console.log('验证失败');
                    }
                });
            }
        }
    };
</script>

<style lang="scss" scoped>
</style>
